package cn.rxls.community.exception.handler;

import cn.rxls.community.enums.ResultEnum;
import cn.rxls.community.exception.BusinessException;
import cn.rxls.community.result.Result;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 全局异常处理
 */

@RestControllerAdvice
public class GlobalExceptionHandling {

    /**
     * 没有捕捉到的异常处理
     */
    @ExceptionHandler(Exception.class)
    public <T> Result<Object> doException(Exception ex){
        System.err.println("未知异常--》"+ex.getMessage());
        ex.printStackTrace();
        return Result.error(ResultEnum.ERROR_EXCEPTION);
    }

    //业务异常处理
    @ExceptionHandler(value = {BusinessException.class})
    public <T> Result<T> doBusinessException(BusinessException ex){
        System.err.println("异常---》"+ex.getException());
        System.err.println("code---------------》"+ex.getCode());
        System.err.println("args---------------》"+ex.getArgs());
        System.err.println("msg---------------》"+ex.getMessage());

        //记录日志

        //返回错误信息

        //如果记录日志失败信息



        return Result.error(ex.getCode(), ex.getMessage());
    }

    //不加@RequestBody注解的校验失败抛BindException异常
    @ExceptionHandler(value = {BindException.class})
    public Result<?> doBusinessException(BindException ex) {
        List<String> msg = ex.getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.toList());
        return Result.error(ResultEnum.ERROR_QUERY, msg);
    }


    /**
     * 添加@RequestBody注解的校验失败抛MethodArgumentNotValidException异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> handleMethodArgumentNotValidException(BindException ex) {
        List<String> msg = ex.getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.toList());
        return Result.error(ResultEnum.ERROR_QUERY, msg);
    }


    /**
     * 基本数据类型添加@NotBlank等注解校验失败抛ConstraintViolationException异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<?> handleConstraintViolationException(ConstraintViolationException ex) {
        List<String> collect = ex.getConstraintViolations()
                .stream().map(ConstraintViolation::getMessageTemplate).collect(Collectors.toList());
        return Result.error(ResultEnum.ERROR_QUERY, collect);


    }

}
